package demo;

import ru.nsu.fit.iconveyor.conveyor.node.InnerNode;
import ru.nsu.fit.iconveyor.conveyor.node.NodeConnection;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Timur Zolotuhin (tzolotuhin@gmail.com)
 */
public class ImageReaderNode extends InnerNode {
    public static final String INPUT_ARG = "input_arg";
    public static final String OUTPUT_RESULT = "output_result";

    public static final String TRANSFER_ARGUMENTS_PARAMETER = "TRANSFER_ARGUMENTS_PARAMETER";

    private final NodeConnection<Object> inputArg;
    private final NodeConnection<Image> outputResult;

    public ImageReaderNode(String id) {
        super(id);

        inputArg = new NodeConnection<Object>(Object.class, NodeConnection.Type.INPUT, INPUT_ARG);
        outputResult = new NodeConnection<Image>(Image.class, NodeConnection.Type.OUTPUT, OUTPUT_RESULT);

        addNodeConnection(inputArg);
        addNodeConnection(outputResult);
    }

    @Override
    public Map<String, Object> execute(Map<String, Object> inputBundles, Properties prop) {
        Map<String, Object> result = new HashMap<String, Object>();

        if (inputBundles.get(INPUT_ARG) != null) {
            Object inputArgBundle = inputBundles.get(INPUT_ARG);
            if (inputArgBundle != null && inputArgBundle.getClass() != null && inputArgBundle.getClass() == String.class) {
                BufferedImage bufferedImage = null;
                try {
                    File imageFile = new File(inputArgBundle.toString());
                    bufferedImage = ImageIO.read(imageFile);

                    int array[][] = new int[bufferedImage.getWidth()][bufferedImage.getHeight()];

                    for (int x = 0; x < bufferedImage.getWidth(); x++) {
                        for (int y = 0; y < bufferedImage.getHeight(); y++) {
                            array[x][y] = bufferedImage.getRGB(x, y);
                        }
                    }
                    Image image = new Image();
                    image.setBitmap(array);
                    image.setName(imageFile.getName());
                    result.put(OUTPUT_RESULT, image);
                } catch(IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

        return result;
    }

    @Override
    public Map<String, Object> preExecute(Map<String, Object> availableInputBundles, Properties prop) {
        if (availableInputBundles.get(INPUT_ARG) == null) {
            return null;
        }
        return availableInputBundles;
    }

    @Override
    public int getOutputToInputRatio() {
        //TODO: check
        return 2;
    }
}
